package auth

import (
	"github.com/gin-gonic/gin"
	v1 "last/app/controllers/v1"
	adminModel "last/app/models/admin"
	"last/app/requests"
	adminRequest "last/app/requests/admin"
	"last/pkg/respose"
	"strconv"
)

type PostController struct {
	v1.BaseController
}

// Store 新增
func (p *PostController) Store(c *gin.Context) {
	var params = adminRequest.PostParams{}
	err := requests.Validator(&params, c)
	if err != nil {
		respose.Failed(c, err.Error())
		return
	}
	var postInfo = &adminModel.Posts{
		Title:         params.Title,
		IsHot:         params.IsHot,
		IsTop:         params.IsTop,
		Banner:        params.Banner,
		Summary:       params.Summary,
		Content:       params.Content,
		ViewsCount:    params.ViewsCount,
		CommentsCount: params.CommentsCount,
		CategoryId:    params.CategoryId,
		Text:          params.Text,
	}

	resultBool := postInfo.Store(postInfo)
	if !resultBool {
		respose.Failed(c, "新增失败")
		return
	}
	respose.Success(c, "", "新增成功")
}

// List 列表
func (p *PostController) List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	pageSize, _ := strconv.Atoi(c.Query("page_size"))
	where := make(map[string]interface{}, 1)
	where["title"] = c.DefaultQuery("title", "")
	where["text"] = c.DefaultQuery("text", "")
	var postInfo = adminModel.Posts{}
	err, total, lists := postInfo.List(page, pageSize, where)
	if err != nil {
		respose.Failed(c, err.Error())
		return
	}
	result := make(map[string]interface{}, 1)
	result["total"] = total
	result["list"] = lists
	respose.Success(c, result, "获取成功")
}

// Edit 更新
func (p *PostController) Edit(c *gin.Context) {
	var params = adminRequest.PostParams{}
	err := requests.Validator(&params, c)
	if err != nil {
		respose.Failed(c, err.Error())
		return
	}
	var postInfo = adminModel.Posts{}
	editData := make(map[string]interface{}, 1)
	editData["title"] = params.Title
	editData["text"] = params.Text
	editData["is_top"] = params.IsTop
	editData["is_hot"] = params.IsHot
	editData["banner"] = params.Banner
	editData["summary"] = params.Summary
	editData["content"] = params.Content
	editData["views_count"] = params.ViewsCount
	editData["comments_count"] = params.CommentsCount
	editData["category_id"] = params.CategoryId
	result := postInfo.Edit(params.Id, editData)
	if result != nil {
		respose.Failed(c, "更新失败")
		return
	}
	respose.Success(c, "", "更新成功")
}

// Show 详情
func (p *PostController) Show(c *gin.Context) {
	id := c.Param("id")
	var postInfo = &adminModel.Posts{}
	err := postInfo.Show(id, postInfo)
	if err != nil {
		respose.Failed(c, "获取失败")
		return
	}
	respose.Success(c, postInfo, "获取成功")
}

// Remove 删除
func (p *PostController) Remove(c *gin.Context) {
	id := c.Param("id")
	var postInfo = adminModel.Posts{}
	err := postInfo.Remove(id, postInfo)
	if err != nil {
		respose.Failed(c, "删除失败")
		return
	}
	respose.Success(c, "", "删除成功")
}
